// 总路由
const Koa  = require('koa')//导入koa包
const {bodyParser} = require("@koa/bodyparser");// 解析 JSON 和 URL 编码的请求体
const Router = require('@koa/router')//导入路由包
const app = new Koa();//实例化应用对象
const cors = require('@koa/cors');
const mount = require('koa-mount');
/* 
1.安装@koa/multer
    npm insall @koa/multer
2.app.js中全局配置图片上传中间件 
*/
const multer = require('@koa/multer');//全局支持多文件上传
const path = require("path");
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '/upload/images'))
    },
    filename(req, file, cb) {
        // 设置 文件名
        const name = file.originalname;
        // 设置文件的后缀名，
        //我这里取的是上传文件的originalname属性的后四位，
        // 即： .png，.jpg等，这样就需要上传文件的后缀名为3位
        const extension = name.substring(name.length - 4);
        cb(null, "img-" + Date.now() + extension);
    },
})

const upload = multer({ storage: storage })
// 全局挂载upload
app.use(upload.array('file', 5));

const router = new Router();//实例化路由---总路由
const travelRouter = require('./routes/travel');//导入子路由--景点
const userRouter = require('./routes/user');//子路由--用户路由
const articleRouter = require('./routes/article')//文章路由
const ticketRouter = require('./routes/ticket')//门票路由
const orderRouter = require('./routes/order')
const commentRouter = require('./routes/comment')
app.use(bodyParser());//针对post请求(使用中间件)


const serve = require('koa-static')//导入koa-static
const {sequelize} =require("./database/index")
app.use(mount('/img',serve(__dirname+'/upload/images')))


// 创建数据库开启.以及更新
;(async function () {
    sequelize.sync({force:false,alter:true})
})()


app.use(cors({
    origin(ctx){
        return '*'//*都可以访问，这里写域名，前端访问的那个
    }
}))


// 配置路由信息---子路由
router.use("/user",userRouter.routes(),userRouter.allowedMethods());
router.use("/travel",travelRouter.routes(),travelRouter.allowedMethods());
router.use("/article",articleRouter.routes(),articleRouter.allowedMethods());
router.use("/ticket",ticketRouter.routes(),ticketRouter.allowedMethods());
router.use("/order",orderRouter.routes(),orderRouter.allowedMethods());
router.use("/comment",commentRouter.routes(),commentRouter.allowedMethods());

// 配置路由信息---总路由（全局中间件）
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000);//监听端口